package com.xt.base.wireless.server;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import com.xt.base.exception.SystemError;

public class JsonUtil {
	/**
	 * 把结果集Map转换为xml格式的字符串。Map中，不能包含有自定义对象。
	 * @param map java.util.Map，必须为<String,Object>类型。其中Object
	 * 不能包含自定义类型，只能是java.util.Map、java.util.Set、java.util.Collection、
	 * String[]、Integer[]、Short[]、Long[]、Float[]、Double[]、Boolean[]，
	 * 或者是以上集中类型的Object[]。
	 * @return xml形式的字符串。
	 */
	public static String parseResultMap2Json(Map<String,Object> map){
		StringBuilder xml = new StringBuilder();
		xml.append("{");
		xml.append(dealMap(map));
		xml.append("}");
		return xml.toString();
	}
	/**
	 * 转换Map类型为xml字符串。
	 * @param map
	 * @return
	 */
	private static String dealMap(Map<String,Object> map){
		Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();
		Map.Entry<String, Object> entry = null;
		StringBuilder xml = new StringBuilder();
		while(iter.hasNext()){
			entry = iter.next();
			if("list".equals(entry.getKey())){
				if(entry.getValue() instanceof Map<?,?>){
					xml.append(",\"").append(entry.getKey()).append("\":[");
					xml.append(dealObject(entry.getValue()));
					xml.append("]");//.append(entry.getKey()).append(">");
				}else{
					xml.append(",\"").append(entry.getKey()).append("\":");
					xml.append(dealObject(entry.getValue()));
				}
			}else if("value".equals(entry.getKey())){
				xml.append(",{\"").append(entry.getKey()).append("\":{");
				xml.append(dealObject(entry.getValue()));
				xml.append("}}");//.append(entry.getKey()).append(">");
			}else{
				xml.append(",\"").append(entry.getKey()).append("\":");
				xml.append(dealObject(entry.getValue()));
				xml.append("");//.append(entry.getKey()).append(">");
			}
			
		}
		
		return xml.substring(1);//xml.toString();
	}
	
	/**
	 * 转换Object类型为xml字符串。
	 * @param o
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private static String dealObject(Object o){
		StringBuilder xml = new StringBuilder();
		if(o==null){
			xml.append("");
		}else if(o instanceof String || o instanceof Integer || o instanceof Long 
			|| o instanceof Float || o instanceof Double || o instanceof Boolean){
			xml.append("\"").append(String.valueOf(o)).append("\"");
			
		}else if(o instanceof Map<?,?>){
			xml.append(dealMap((Map<String,Object>)o));
			
		}else if(o instanceof Collection<?>){
			xml.append(dealCollection((Collection<Object>)o));
			
		}else if(o instanceof String[]){
			xml.append(dealPrototypeArray((String[])o));
			
		}else if(o instanceof Integer[]){
			xml.append(dealPrototypeArray((Integer[])o));
			
		}else if(o instanceof Short[]){
			xml.append(dealPrototypeArray((Short[])o));
			
		}else if(o instanceof Long[]){
			xml.append(dealPrototypeArray((Long[])o));
			
		}else if(o instanceof Float[]){
			xml.append(dealPrototypeArray((Float[])o));
			
		}else if(o instanceof Double[]){
			xml.append(dealPrototypeArray((Double[])o));
			
		}else if(o instanceof Boolean[]){
			xml.append(dealPrototypeArray((Boolean[])o));
			
		}else if(o instanceof Object[]){
			xml.append(dealObjectArray((Object[])o));
		}else{
			throw new SystemError(new Object(),new Object[]{},"不支持使用自定义对象作为结果集！");
		}
		
		return xml.toString();
	}
	
	/**
	 * 转换Collection类型为xml字符串
	 * @param coll
	 * @return
	 */
	private static String dealCollection(Collection<Object> coll){
		StringBuilder xml = new StringBuilder();
		//xml.append("[");
		Iterator<Object> iter = coll.iterator();
		Object o = null;
		while(iter.hasNext()){
			o = iter.next();
			if(o instanceof String || o instanceof Integer || o instanceof Long 
				|| o instanceof Float || o instanceof Double || o instanceof Boolean){
				xml.append(",{\"value\":\"").append(String.valueOf(o)).append("\"}");
				
			}else{
				xml.append(",{")
				.append(dealObject(o))
				.append("}");
			}
		}
		if (xml.length()==0) {
			return "[]";
		}
		//xml.append("]");
		//return xml.toString();
		return "["+xml.substring(1)+"]";
	}
	
	/**
	 * 转换原型数组为xml字符串。
	 * 这里的Object[]只能是原型类型的数组，否则转换得到的内容是哈希字符串。
	 * @param array
	 */
	private static String dealPrototypeArray(Object[] array){
		StringBuilder xml = new StringBuilder();
		//xml.append("[");
		for(Object s : array){
			xml.append("{\"value\":\"")
			.append(s.toString())
			.append("\"}");
		}
		if (xml.length()==0) {
			return "[]";
		}
		//xml.append("]");
		//return xml.toString();
		return "["+xml.substring(1)+"]";
	}
	
	/**
	 * 转换Object[]数据为xml字符串。
	 * @param array
	 * @return
	 */
	private static String dealObjectArray(Object[] array){
		StringBuilder xml = new StringBuilder();
		//xml.append("[");
		for(Object o : array){
			if(o instanceof String || o instanceof Integer || o instanceof Long 
					|| o instanceof Float || o instanceof Double || o instanceof Boolean){
					xml.append(",{\"value\":\"").append(String.valueOf(o)).append("\"}");
			}else{
				xml.append(",{")
				.append(dealObject(o))
				.append("}");
			}
		}
		if (xml.length()==0) {
			return "[]";
		}
		//xml.append("]");
		//return xml.toString();
		return "["+xml.substring(1)+"]";
	}
	
	
	public static String xml2Json(String xml){
		Map<String,Object> map = MobileActionUtil.parseRequestXml(xml);
		//String s = map.toString();
		String s = parseResultMap2Json(map);
		return s;
	}
	
	public static void main(String[] args){
		
		try {
			String file = "D:\\OA+政务\\-------\\楚矿\\xml\\便签列表.xml";
			Document  doc = new SAXReader().read(new File(file));
			System.out.println("便签列表:\n"+JsonUtil.xml2Json(doc.asXML()));
			
			file = "D:\\OA+政务\\-------\\楚矿\\xml\\登陆成功.xml";
			doc = new SAXReader().read(new File(file));
			System.out.println("登陆成功:\n"+JsonUtil.xml2Json(doc.asXML()));
			
			file = "D:\\OA+政务\\-------\\楚矿\\xml\\人员机构树.xml";
			doc = new SAXReader().read(new File(file));
			System.out.println("人员机构树:\n"+JsonUtil.xml2Json(doc.asXML()));
			
			file = "D:\\OA+政务\\-------\\楚矿\\xml\\通知公告列表.xml";
			doc = new SAXReader().read(new File(file));
			System.out.println("通知公告列表:\n"+JsonUtil.xml2Json(doc.asXML()));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
